package com.glorystone.ins.controller;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.glorystone.ins.domain.SysAuth;
import com.glorystone.ins.domain.SysUser;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import com.glorystone.ins.common.JsonResult;
import com.glorystone.ins.common.common.DataTable;
import com.glorystone.ins.common.common.PageVo;
import com.glorystone.ins.domain.SysRole;
import com.glorystone.ins.interceptor.PageList;
import com.glorystone.ins.service.ISysAuthService;
import com.glorystone.ins.service.ISysRoleService;
import com.glorystone.ins.vo.RootMenu;

/**
 * 角色controller
 *
 */
@Controller
@RequestMapping("/sysrole")
public class SysRoleController extends BaseController {

    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private ISysAuthService sysAuthService;

    /**
     * 去往角色管理列表
     */
    @RequestMapping("/tolist")
    public ModelAndView tolist(ModelAndView mv){
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        String roleIds = user.getRoleId();
        List<SysAuth> list  = sysAuthService.getAuthByRoleId(roleIds);
        List<SysAuth> rootMenu = Lists.newArrayList();
        List<SysAuth> childMenu = Lists.newArrayList();
        List<SysAuth> childPage = Lists.newArrayList();
        List<SysAuth> childButton = Lists.newArrayList();
        for(SysAuth s:list){
            String level = ""+s.getLevel();
            if("1".equals(level)){
                rootMenu.add(s);
            }else if("2".equals(level)){
                childMenu.add(s);
            }else if("3".equals(level)){
                childPage.add(s);
            }else if("9".equals(level)){
                childButton.add(s);
            }
        }
        List<Map<String,Object>> departmentList = sysRoleService.getAllInOutDepartment();
        List<Map<String,Object>> departList = Lists.newArrayList();
        String officeId = ""+user.getOfficeId();
        if(!"1".equals(officeId)){
            for(Map<String,Object>map:departmentList){
                String tid = ""+map.get("tid");
                if(officeId.equals(tid)){
                    departList.add(map);
                }
            }
        }else{
            departList = departmentList;
        }
        mv.addObject("roleIds", roleIds);
        mv.addObject("rootMenu", rootMenu);
        mv.addObject("childMenu", childMenu);
        mv.addObject("childPage", childPage);
        mv.addObject("childButton", childButton);
        mv.addObject("departmentList", departList);
        mv.setViewName("system/sysRole");
        return mv;
    }

    /**
     * 组装角色列表数据
     */
    @SuppressWarnings({ "unchecked", "rawtypes" })
	@RequestMapping(value="/queryTableData",method = RequestMethod.GET)
    @ResponseBody
    public DataTable<SysRole> queryTableData(HttpServletRequest request) {
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        PageVo vo =  parametToPageVoData(request,SysRole.class,user);
        PageList<SysRole> list = sysRoleService.queryAllRoleList(vo);
        DataTable data = resultToDataTable(list);
        return data;
    }


    /**
     * 去往新增-角色
     */
    @RequestMapping("/toadd")
    public ModelAndView toAdd(ModelAndView mv){
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        String roleIds = user.getRoleId();
        List<SysAuth> list  = sysAuthService.getAuthByRoleId(roleIds);
        List<SysAuth> rootMenu = Lists.newArrayList();
        List<SysAuth> childMenu = Lists.newArrayList();
        List<SysAuth> childButton = Lists.newArrayList();
        for(SysAuth s:list){
            String level = ""+s.getLevel();
            if("1".equals(level)){
                rootMenu.add(s);
            }else if("2".equals(level)){
                childMenu.add(s);
            }else if("9".equals(level)){
                childButton.add(s);
            }
        }
        List<Map<String,Object>> departmentList = sysRoleService.getAllDepartment();
        mv.addObject("rootMenu", rootMenu);
        mv.addObject("childMenu", childMenu);
        mv.addObject("childButton", childButton);
        mv.addObject("departmentList", departmentList);
        mv.addObject("type", "A");
        mv.setViewName("system/sysrole_add");
        return mv;
    }

    /**
     * 去往编辑-角色
     */
    @RequestMapping("/toedit/{id}")
    public @ResponseBody
    JsonResult toEdit(@PathVariable Long id/*, ModelAndView mv*/){
        /*SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        Long roleId = user.getRoleId();
        List<SysAuth> list  = sysAuthService.getAuthByRoleId(roleId);
        List<SysAuth> rootMenu = Lists.newArrayList();
        List<SysAuth> childMenu = Lists.newArrayList();
        List<SysAuth> childButton = Lists.newArrayList();
        for(SysAuth s:list){
            String level = ""+s.getLevel();
            if("1".equals(level)){
                rootMenu.add(s);
            }else if("2".equals(level)){
                childMenu.add(s);
            }else if("9".equals(level)){
                childButton.add(s);
            }
        }
        List<Map<String,String>> departmentList = sysRoleService.getAllDepartment();
        mv.addObject("rootMenu", rootMenu);
        mv.addObject("childMenu", childMenu);
        mv.addObject("childButton", childButton);
        mv.addObject("role", sysRoleService.getRoleById(id));
        mv.addObject("departmentList", departmentList);
        mv.addObject("type", "E");
        mv.setViewName("system/sysrole_add");*/
        SysRole role = sysRoleService.getRoleById(id);
        return JsonResult.createSuccess(role);
    }

    /**
     * 添加/编辑-角色
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    @ResponseBody
    public Map<String,String> addUser(SysRole sysRole,@RequestParam(value = "idList") String[] idList) {
        Map<String,String> resualtMap = Maps.newHashMap();
        resualtMap.put("type","E");
        boolean result = false;
        String authIds = "0";
        SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
        for(int i=0;i<idList.length;i++){
            authIds += ","+idList[i];
        }
        authIds+=",";
        sysRole.setAuthIds(authIds);
        if(sysRole.getTid() != null && sysRole.getTid() > 0){
            sysRole.setUpdateTime(LocalDateTime.now());
            sysRole.setUpdateBy(Long.valueOf(user.getTid()));
            result = sysRoleService.updateRole(sysRole);
        }else{
            sysRole.setDelFlag(0);
            sysRole.setStatus(0);
            sysRole.setCreateBy(Long.valueOf(user.getTid()));
            sysRole.setCreateTime(LocalDateTime.now());
            result = sysRoleService.addRole(sysRole);
        }
        if(result){
            resualtMap.put("type","S");
        }
        return resualtMap;
    }

    /**
     * 启用禁用角色
     */
    @RequestMapping("/uprole")
    public @ResponseBody
    JsonResult delUser(@RequestParam String tid,@RequestParam String flag){
        if(!Strings.isNullOrEmpty(tid) && !Strings.isNullOrEmpty(flag)){
            SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
            SysRole role = new SysRole();
            role.setTid(Long.parseLong(tid));
            role.setUpdateTime(LocalDateTime.now());
            role.setUpdateBy(user.getTid());
            role.setStatus(Integer.parseInt(flag));
            boolean result = sysRoleService.updateRole(role);
            if(result){
                return returnSuccess("操作成功！");
            }
        }
        return JsonResult.createErrorMsg("操作失败！");
    }
    
    /**
     * 验证新增角色是否已经添加
     */
    @RequestMapping("/only/{name}")
    public @ResponseBody JsonResult onlyUser(@PathVariable String name){
        List<SysRole> sysRoleList = sysRoleService.checkRoleByName(name);
        if(sysRoleList == null || sysRoleList.size() == 0){
            return returnSuccess("角色还没添加");
        }else{
            return JsonResult.createErrorMsg("角色已经添加");
        }
    }

    @ResponseBody
    @RequestMapping(value="/getDataType",method=RequestMethod.POST)
    public Map<String,Object> getDataType(@RequestParam String tid){
        Map<String,Object> resultMap = Maps.newHashMap();
        resultMap.put("type","E");
        if(!Strings.isNullOrEmpty(tid)){
            Long id = Long.parseLong(tid);
            List<Map<String,String>> dataList = sysRoleService.getRoleType(id);
            resultMap.put("dataList",dataList);
            resultMap.put("type","S");
        }
        return resultMap;
    }

}
